<template>
  <div class="app-container">

    <list-page-container>

      <template slot="query">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="90px">
          <el-form-item label="用户姓名" prop="userName">
            <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户姓名"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户手机号" prop="phone">
            <el-input
                v-model="queryParams.phone"
                placeholder="请输入用户手机号"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="用户状态" prop="userState">
            <el-select v-model="queryParams.userState" placeholder="用户状态" clearable>
              <el-option
                  v-for="dict in dict.type.enum_user_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地域" prop="userState">
            <div style="height: 100%;width: 220px">
              <treeselect v-model="queryParams.orgCode" :options="deptOptions"
                          :normalizer="normalizer"
                          placeholder="选择地域"/>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <template slot="handel">
        <el-row class="handle-container" :gutter="10">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
            >删除
            </el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button-->
<!--                type="warning"-->
<!--                plain-->
<!--                icon="el-icon-download"-->
<!--                size="mini"-->
<!--                @click="handleExport"-->
<!--            >导出-->
<!--            </el-button>-->
<!--          </el-col>-->
        </el-row>
      </template>

      <template slot="table">
        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="用户姓名" align="center" prop="userName"/>
          <el-table-column label="用户手机号" align="center" prop="phone"/>
          <el-table-column label="所属地域" align="center" prop="orgName"/>
          <el-table-column label="角色" align="center" prop="role"/>
          <el-table-column label="用户状态" align="center" prop="userState">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.enum_user_state" :value="scope.row.userState"/>
            </template>
          </el-table-column>
          <el-table-column width="400" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                  v-if="scope.row.userType==null"
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="authorityButton(scope.row)"
              >权限管理
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
              >删除
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleResetPwd(scope.row)"
              >重置密码
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <template slot="pageDisplay">
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
      </template>
    </list-page-container>


    <el-dialog :title="title" :visible.sync="open" width="530px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属地域" prop="orgCode">
          <treeselect :disabled="hanType == OPERATE_TYPE.UPDATE" v-model="form.orgCode" :options="deptOptions"
                      :normalizer="normalizer"
                      placeholder="选择地域"/>
        </el-form-item>
        <el-form-item label="用户姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名"/>
        </el-form-item>
        <el-form-item label="用户手机号" prop="phone">
          <el-input :disabled="hanType == OPERATE_TYPE.UPDATE" v-model="form.phone" placeholder="请输入用户手机号"/>
        </el-form-item>
        <el-form-item label="用户状态" prop="userState">
          <el-select  v-model="form.userState">
            <el-option
                v-for="dict in dict.type.enum_user_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    权限管理弹窗-->
    <el-dialog :title="'管理权限'" :visible.sync="open2" width="530px" append-to-body>
      <el-form ref="form2" :model="form2"  label-width="100px">
        <el-form-item label="角色">
          <el-select  v-model="form2.role">
            <el-option
                v-for="dict in authorityOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addAuthority">添加</el-button>
        <el-button @click="cancelAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSysUser,
  delSysUser, getCurrentUserAllowUserType,
  getSysUserInfoById,
  getSysUserList,
  resetPwd,
  updateSysUser,
  getAllowSelectUserType,
  setUserType
} from "@/api/system/sysUser";
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import {OPERATE_TYPE} from "@/constantData";

export default {
  dicts: ['enum_user_state', 'enum_user_type'],
  components:{Treeselect},
  name: "sysUser_list",
  data() {
    return {
      //条目id
      itemId: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        phone: null,
        userName: null,
        userState: null,
      },
      dataList: [],
      total: 0,
      loading: false,
      multiple: true,
      open: false,
      open2: false,
      // 弹出层标题
      title: "",
      form: {},
      baseForm: {
        phone: null,
        userName: null,
        userState: null,
        orgCode:null,
      },
      // 表单校验
      rules: {
        phone: [
          {required: true, message: "用户手机号不能为空", trigger: "blur"}
        ],
        userName: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"}
        ],
        userState: [
          {required: true, message: "用户状态不能为空", trigger: "change"}
        ],
        orgCode: [
          {required: true, message: "所属地域不能为空", trigger: "change"}
        ],
      },
      //管理权限弹窗表单数据
      form2: {
        role:null,
      },
      // 选中数组
      ids: [],
      deptOptions:[],
      hanType:'',
      OPERATE_TYPE,
      //角色下拉列表配置
      authorityOptions:[],
    }
  },
  methods: {
    /** 转换地域数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.orgCode,
        label: node.orgName,
        children: node.children
      };
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
      }).then(({value}) => {
        resetPwd({id: row.id, pwd: value}).then(response => {
          this.$modal.msgSuccess("修改成功，新密码是：" + value);
        });
      }).catch(() => {
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const dictId = row.id
      this.hanType = OPERATE_TYPE.UPDATE
      getSysUserInfoById(dictId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 导出按钮操作 */
    handleExport() {

    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除当前数据项？').then(function () {
        return delSysUser(dictIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //取消添加角色按钮回调
    cancelAdd(){
      this.open2 = false;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSysUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSysUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**
     * 添加按钮回调
     */
    addAuthority(){
      let params = {
        id:this.itemId,
        userType:this.form2.role,
      }
      //发请求
      setUserType(params).then(res => {
        //关弹窗
        this.open2 = false;
        this.$modal.msgSuccess('角色添加成功')
        this.getList();
      })

      //关弹窗
      this.open2 = false;
      this.$modal.msgSuccess('角色添加成功')
    },
    // 表单重置
    reset() {
      this.form = _.cloneDeep(this.baseForm);
      this.resetForm("form");
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.hanType = OPERATE_TYPE.ADD
      this.open = true;
      this.title = "添加用户";
    },
    /**
     * 权限管理按钮
     */
    authorityButton(row){
      this.itemId = row?.id;
      this.form2.role = null
      this.open2 = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      getSysUserList(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
      );
    },
    getDeptList(){
      let owner = this
      listDept().then(response => {
        owner.deptOptions = this.handleTree(response.data, "orgCode", 'parentCode');
      });
    },

    //获取角色下拉列表方法
    getAuthorityOptions(){

      getAllowSelectUserType().then((res) => {
        if(res && res.code==200 && res.data){
          if(Array.isArray(res.data)){
            this.authorityOptions=res.data;
          }
        }

      })

    }
  },
  created() {
    this.getList();
    this.getDeptList();


  },
  mounted(){
    this.getAuthorityOptions();
  }
}
</script>

<style scoped>

</style>
